<template>
    <el-button class="countdown-button" :size="size" @click="codeStart" link>
        {{ getCodeText }}
    </el-button>
</template>

<script lang="ts" setup>
import { unref, computed } from "vue";
import { useCountdown } from "@/composables/useCountDown";
import { messageSuccess } from "@/utils/message";

const props = defineProps({
    // 尺寸大小
    size: {
        type: String as any,
        validator: (v: string) => ["default", "large", "small"].includes(v),
        default: "large",
    },
    // 倒计时秒数
    count: {
        type: Number,
        default: 60,
    },
    // api接口参数
    apiParams: {
        type: Object,
        default: {},
    },
    // api接口
    sendCodeApi: {
        type: Function,
        default: null,
    },
    // 初始提示
    initText: {
        type: String,
        default: "获取验证码",
    },
    // 倒计时中的提示
    changeText: {
        type: String,
        default: "x秒后重新获取",
    },
});

const { currentCount, isStart, start, stop, reset } = useCountdown(props.count);

// 开始发送
const codeStart = async () => {
    if (
        !unref(isStart) &&
        props.sendCodeApi &&
        typeof props.sendCodeApi == "function"
    ) {
        await props.sendCodeApi(props.apiParams);
        messageSuccess("发送成功");
    }
    start();
};

// 倒计时停止
const codeStop = () => {
    stop();
};

// 倒计时重置
const codeReset = () => {
    reset();
};

// 获取倒计时文字
const getCodeText = computed(() => {
    return !unref(isStart)
        ? props.initText
        : props.changeText.replace("x", `${unref(currentCount)}`);
});

defineExpose({
    codeStart,
    codeStop,
    codeReset,
    getCodeText,
});
</script>

<style lang="scss" scoped></style>
